package com.gljx.web.controller;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.gljx.util.CommonExport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.gljx.util.GetFid;
import com.gljx.util.GetFnumber;
import com.gljx.util.TimeFormat;
import com.gljx.util.stateToString;
import com.gljx.web.Entity.Clazz;
import com.gljx.web.Entity.Department;
import com.gljx.web.Entity.PageBean;
import com.gljx.web.Entity.User;
import com.gljx.web.service.ClazzService;
import com.gljx.web.service.CustomLogService;
import com.gljx.web.service.DepartmentService;

@Controller
@RequestMapping("/")
public class ClazzController {

	//自动注入
	@Autowired
	private ClazzService clazzService;

	//自动注入
	@Autowired
	private DepartmentService departmentService;

	//自动注入
	@Autowired
	private CustomLogService customLogService;

	/**
	 * 查询班级
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping("/queryClazz/look.action")
	public String queryClazz(HttpServletRequest request, String flag) {
		PageBean<Clazz> pb = new PageBean<>();
		//获取操作人信息
		User user = (User) request.getSession().getAttribute("user");
		try {
			//获取分页
			pb = getPageBean(request, user.getFcompanyid(), null);
			//获取分页数据
			List<Clazz> clazzs = pb.getBeanList();
			//把数据传到页面
			request.setAttribute("pb", pb);
			request.setAttribute("clazzs", clazzs);
			request.setAttribute("flag", flag);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "/backHome/studentData/clazz/clazzList";
	}

	/**
	 * 根据班级名称查询
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping("/queryClazzByFnameL2")
	public String queryClazzByFnameL2(HttpServletRequest request, String fnameL2) {
		//获取操作人信息
		User user = (User) request.getSession().getAttribute("user");
		PageBean<Clazz> pb = new PageBean<>();
		//去除空格
		fnameL2 = fnameL2.trim();
		if ("".equals(fnameL2)) {
			queryClazz(request, null);//为空就调用查询方法
		} else {
			try {
				//查询数据
				pb = getPageBean(request, user.getFcompanyid(), fnameL2);
				List<Clazz> clazzs = pb.getBeanList();
				//把数据传到页面上
				request.setAttribute("pb", pb);
				request.setAttribute("clazzs", clazzs);
				request.setAttribute("fnameL2", fnameL2);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return "/backHome/studentData/clazz/clazzList";
	}

	/**
	 * 跳转到添加页面
	 *
	 * @return
	 */
	@RequestMapping("/insertClazz")
	public String insertClazz(HttpServletRequest request, String type) {
		//获取操作人信息
		User user = (User) request.getSession().getAttribute("user");
		//获取组织
		Department department = departmentService.queryAdminByFid(user.getFcompanyid());
		//获取上一个编码
        /*String number = customLogService.selectFunmber("ct_ds_clazz",user.getFcompanyid());*/
		//获取编码
		String fnumber = GetFnumber.fnumbers("ZBJ");
		//查询所有车型
		List<String> carTypes = customLogService.queryCarTypeAll();
		//把数据传到页面
		request.setAttribute("carTypes", carTypes);
		request.setAttribute("fnumber", fnumber);
		request.setAttribute("department", department);
		request.setAttribute("type", type);
		return "/backHome/studentData/clazz/addAndUpdate";
	}

	/**
	 * 根据fid判断添加或者修改
	 *
	 * @param request
	 * @param clazz   属性自动封装
	 * @return
	 */
	@RequestMapping("/modifyOrAddClazz")
	public String modifyOrAddClazz(HttpServletRequest request, Clazz clazz) {
		//获取操作人信息
		User user = (User) request.getSession().getAttribute("user");
		//控制单元id
		clazz.setFcontrolunitid(user.getFcompanyid());
		//公司id
		clazz.setCfficompanyid(user.getFcompanyid());
		//获取当前时间
		String time = TimeFormat.timeFormat(new Date());
		if ("".equals(clazz.getFid()) || null == clazz.getFid()) {
			//创建人id
			clazz.setFcreatorid(user.getFid());
			//利用UUID生成fid
			clazz.setFid(GetFid.UUIDIntoFid());
			//当前创建时间
			clazz.setFcreatetime(time);
			//添加
			clazzService.addClazz(clazz);
			//添加日志
			customLogService.addLog("学员基础资料", time + "对班级进行添加操作", null, user.getFid());
			//重定向到添加页面
			return "redirect:/DrivingSys/insertClazz?type=3";
		} else {
			//修改时间
			clazz.setFlastupdatetime(time);
			//修改人id
			clazz.setFlastupdateuserid(user.getFid());
			//修改
			clazzService.modifyClazz(clazz);
			//添加日志
			customLogService.addLog("学员基础资料", time + "对班级进行修改操作", null, user.getFid());
			//调用查询方法
			return commonController.skipUrl("/queryClazz/look.action");
		}

	}

	/**
	 * 根据fid查询
	 *
	 * @param request
	 * @param fid
	 * @return
	 */
	@RequestMapping("/selectClazzByFid")
	public String selectClazzByFid(HttpServletRequest request, String fid) {
		//获取操作人信息
		User user = (User) request.getSession().getAttribute("user");
		//获取组织
		Department department = departmentService.queryAdminByFid(user.getFcompanyid());
		//根据fid查询
		Clazz clazz = clazzService.selectClazz(user.getFcompanyid(), fid, "", "").get(0);
		//查询所有车型
		List<String> carTypes = customLogService.queryCarTypeAll();
		//把数据传到页面
		request.setAttribute("carTypes", carTypes);
		request.setAttribute("department", department);
		request.setAttribute("fid", fid);
		request.setAttribute("clazz", clazz);
		return "/backHome/studentData/clazz/addAndUpdate";
	}

	/**
	 * 根据fid删除
	 *
	 * @param request
	 * @param deleteId 要删除的fid，可以多个
	 * @return
	 */
	@RequestMapping("/deleteClazzByFid")
	public String deleteClazzByFid(HttpServletRequest request, String deleteId[], String fid) {
		//获取操作人信息
		User user = (User) request.getSession().getAttribute("user");
		//删除
		if (fid == null || "".equals(fid)) {
			for (int i = 0; i < deleteId.length; i++) {
				clazzService.deleteClazzByFid(deleteId[i]);
			}
		} else {
			clazzService.deleteClazzByFid(fid);
		}

		//添加日志
		customLogService.addLog("学员基础资料", TimeFormat.timeFormat(new Date()) + "对班级进行删除操作", null, user.getFid());
		//调用查询方法
		queryClazz(request, null);
		return "/backHome/studentData/clazz/clazzList";
	}

	/**
	 * 根据ID查找班级
	 *
	 * @param id
	 * @return
	 * @createTime 2017-11-6 2:20 pm
	 * @author zyq.
	 */
	@RequestMapping(value = "/selClazzById")
	@ResponseBody
	public List<Clazz> selClazzById(String id) {
		List<Clazz> clazzs = new ArrayList<>();
		String[] ids = id.split(",");
		for (int i = 0; i < ids.length; i++) {                                           //获取多个ID
			Clazz clazz = clazzService.selClazzById(ids[i]);
			clazzs.add(clazz);
		}
		return clazzs;
	}


	@SuppressWarnings("unchecked")
	/**
	 * 返回PageBean实体类  包括记录总数，页码，每页记录集等  dmz 20160921
	 * @return 返回PageBean实体类
	 * @throws Exception
	 */
	public PageBean<Clazz> getPageBean(HttpServletRequest request, String companyId, String fnameL2) throws Exception {

		int offset;//从第几条数据开始加载
		if (request.getParameter("pager.offset") == null) {
			offset = 0;
		} else {
			offset = Integer.parseInt(request.getParameter("pager.offset"));
		}
		//拼接SQL语句
		StringBuffer psql = new StringBuffer();
		psql.append("select to_char(t.FCREATETIME,'YYYY-MM-DD HH24:MI:SS') fcreatetime,to_char(t.FLASTUPDATETIME,'YYYY-MM-DD HH24:MI:SS') flastupdatetime,");
		psql.append("t.fid,t.cftime,t.fnumber,t.fname_l2 fnameL2,t.fsimplename,t.fdescription_l2 fdescriptionL2,u.name createName,c.name updateName,");
		psql.append("t.cfsycl,t.cfksf,t.cflc,t.cfprice,t.cfvip,t.cftx,t.cfstate from ct_ds_clazz t left join t_e_user u on t.fcreatorid=u.fid ");
		psql.append(" left join t_e_user c on t.flastupdateuserid=c.fid where t.fcontrolunitid= '" + companyId + "'");
		if (fnameL2 == null || "".equals(fnameL2)) {

		} else {
			psql.append(" and t.fname_l2 like '%" + fnameL2 + "%'");
		}
		psql.append("order by t.fcreatetime desc");
		int psize = 100; //每页显示数
		int pindex = offset / psize;//+1  页码从0开始
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap = clazzService.selectPage(pindex, psql.toString(), psize);
		PageBean<Clazz> pb = new PageBean<>();
		pb.setPc(pindex); //页码
		Map<String, Object> paramMapCount = getPageBeanCount(psql.toString()); //取记录总数
		pb.setTr((int) paramMapCount.get("Pcount")); //记录总数
		pb.setPs(psize);
		pb.setBeanList((List<Clazz>) paramMap.get("v_cur")); //每页数据集
		return pb;
	}

	/**
	 * 取记录总数 dmz 20160921
	 *
	 * @param psql SQL语句
	 * @return Map
	 * @throws Exception
	 */
	public Map<String, Object> getPageBeanCount(String psql) throws Exception {

		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap = clazzService.selectPageCount(psql);
		return paramMap;
	}


	//-----------------------------------------导出excel-------------------------------------------

	/**
	 * 导出Execl
	 *
	 * @param response
	 */
	@RequestMapping("/importClazz")
	public void importClazz(HttpServletResponse response, HttpServletRequest request, String fnameL2) {
		//获取操作人信息
		User user = (User) request.getSession().getAttribute("user");
		List<Object> data = new ArrayList<>();
		//查询数据
		List<Clazz> Clazzs = clazzService.selectClazzExcel(fnameL2.trim(), user.getFcompanyid());
		for (Clazz clazz : Clazzs) {
			data.add(clazz.getFnumber());//班级编号
			data.add(clazz.getFnameL2());//班级名称名称
			data.add(clazz.getFsimplename());//班级简称
			data.add(clazz.getFdescriptionL2());//备注
			data.add(clazz.getFcreatetime());//创建时间
			data.add(clazz.getFlastupdatetime());//最后修改时间
			data.add(clazz.getCreateName());//创建人
			data.add(clazz.getUpdateName());//修改人
			data.add(clazz.getCfsycl());//适用车辆
			data.add(stateToString.whether(clazz.getCfksf()));//是否包含考试费
			data.add(stateToString.whether(clazz.getCflc()));//是否包含练车
			data.add(clazz.getCfprice());//金额
			data.add(stateToString.whether(clazz.getCfvip()));//是否vip
			data.add(stateToString.whether(clazz.getCftx()));//是否特训班
			if (clazz.getCftime() != null && !clazz.getCftime().equals("")) {//是否计时预约
				if (clazz.getCftime() == "1") {
					data.add("是");
				} else {
					data.add("否");
				}
			} else {
				data.add("否");
			}
			if (clazz.getCfstate() == null) {
				data.add("");
			} else if (clazz.getCfstate() == 1) {
				data.add("启用");
			} else {
				data.add("禁用");
			}


		}

		//头部数据
		String head[] = {"班级编码", "班级名称", "班级简称", "备注", "创建时间", "最后修改时间",
				"创建人", "修改人", "适用车辆", "是否包含考试费", "是否包含练车", "金额", "VIP", "特训班", "计时班", "状态"};
		//长度
		Integer length[] = {5000, 7000, 5000, 5000, 6200, 6200, 2600, 2600, 2600, 3000, 3000, 3000, 3000, 3000, 3000, 3000};
		try {
			//导出Excel
			CommonExport.importExcel(response, "班级" + TimeFormat.getNowTime2() + ".xls", "班级", data, head, length);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}